#if DEBUG_VERSION
if (!dafos) {
  throw new Error("Dafos namespace not found!");
}
#endif

#if TOOLSTAB

dafos.onToolsTabActivated = function() {
  if (dafos.toolstab == null) {
    dafos.toolstab = new dafos.ToolsTab(document.getElementById("toolstab"), dafos.ui);
  }
  TRACK("tab/tools");
  RESIZE();
};

/**
 * Constructor
 */
dafos.ToolsTab = function(parent, ui) {
  LOG("[ToolsTab]");
  this.appengine = new dafos.AppEngine();
  var callbacks = {
    "clearcache" : dafos.bind(this.clearCache, this)
  }
  this.gadgetui = ui;
  this.ui = new dafos.ToolsTabUI(parent, callbacks);
#ifdef DEVELOPMENT
  this.requestToolsPage();
#endif
};

dafos.ToolsTab.prototype.clearCache = function() {
  this.gadgetui.showLoading("clearcache");
  this.appengine.clearCache(this.ui.getUrl(), 
      dafos.bind(this.onCacheCleared, this)); 
};

dafos.ToolsTab.prototype.onCacheCleared = function(data) {
  LOG("[onCacheCleared]", "data", data);
  this.gadgetui.hideLoading("clearcache");
  this.gadgetui.setMessage(data.message);
};

dafos.ToolsTab.prototype.requestToolsPage = function() {
  this.gadgetui.showLoading("tools");
  var url = "@server.deploy.base@/tools/";
  LOG("requesting tools url", url);
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
      gadgets.io.ContentType.TEXT;
  gadgets.io.makeRequest(url, dafos.bind(this.onToolsPage, this), params);
};

dafos.ToolsTab.prototype.onToolsPage = function(data) {
  LOG("[onToolsPage]", data);
  this.gadgetui.hideLoading("tools"); 
  var corpus = data.text.toLowerCase();
  var startindex = corpus.indexOf('<!-- startcontent -->');
  if (startindex != -1) {
    startindex += 21;
  }
  var endindex = corpus.indexOf("<!-- endcontent -->");
  this.ui.renderToolsPage(data.text.substring(startindex, endindex));
};


/**
 * Constructor
 */
dafos.ToolsTabUI = function(parent, callbacks) {
  LOG("[ToolsTabUI]");
  this.dom_parent = parent;
  this.dom_content_ = e34.$("toolstab_content");
  this.render(callbacks);
};

dafos.ToolsTabUI.prototype.render = function(callbacks) {
 #if ORKUT
  var button_attrs = {
    "onclick" : callbacks.clearcache
  };
  var table_attr = {
    "className" : "dafos-tools-cachetable"
  }; 
  
  var input_td_attr = {
    "className" : "inputcell"
  };
  
  this.refreshButton = w23.e("button", button_attrs, "Refresh cache");
  this.inputBox = w23.e("input");  
  this.dom_parent.appendChild(
    w23.e("table", table_attr, 
      w23.e("tbody", null,
        w23.e("tr", null, 
          w23.e("td", input_td_attr, this.inputBox),
          w23.e("td", null, this.refreshButton)))));          
#endif

  e34.$("toolstab").removeClass("hidden");
};

dafos.ToolsTabUI.prototype.renderToolsPage = function(text) {
  this.dom_content_.removeAllChildren();
  this.dom_content_.getElement().innerHTML = text;
  RESIZE();
};

dafos.ToolsTabUI.prototype.getUrl = function() {
  return this.inputBox.value;
};

#endif
